// @APIVersion 1.0.0
// @Title beego Test API
// @Description beego has a very cool tools to autogenerate documents for your API
// @Contact astaxie@gmail.com
// @TermsOfServiceUrl http://beego.me/
// @License Apache 2.0
// @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html
package routers

import (
	"api01/controllers"
	"api01/models"
	"api01/util"
	"github.com/astaxie/beego/context"

	"github.com/astaxie/beego"
)

func init() {
	//先给ctx赋值
	beego.InsertFilter("/*",beego.BeforeRouter,func(ctx *context.Context) {
		util.OutPutInit(ctx)
	})

	ns := beego.NewNamespace("/v1",
		beego.NSNamespace("/user",
			beego.NSBefore(FilterUser),
			beego.NSInclude(
				&controllers.UserController{},
			),
		),
		beego.NSNamespace("/admin",
			beego.NSBefore(FilterAdminUser),
			beego.NSNamespace("/role",
				beego.NSInclude(
					&controllers.RoleController{},
				),
			),
			beego.NSNamespace("/group",
				beego.NSInclude(
					&controllers.GroupController{},
				),
			),
		),
		beego.NSInclude(
			&controllers.LoginController{},
		),
	)
	beego.AddNamespace(ns)


}

//验证用户token
func FilterUser(ctx *context.Context) {
	token := ctx.Input.Header("authorization")
	if len(token)==0 {
		util.OutPutError(403,"TOKEN丢失")
		return
	}
	claims, success := util.ValidateToken(token)
	if !success {
		util.OutPutError(403,"TOKEN异常")
		return
	}

	if claims.UserType != models.USER_TYPE_ORIDINARY {
		util.OutPutError(403,"用户类型异常")
		return
	}
	controllers.UserId = claims.UserId
}

//验证管理员token
func FilterAdminUser(ctx *context.Context) {
	token := ctx.Input.Header("authorization")
	if len(token) == 0 {
		util.OutPutError(403,"TOKEN丢失")
		return
	}
	claims, success := util.ValidateToken(token)
	if !success {
		util.OutPutError(403,"TOKEN异常")
		return
	}
	if claims.UserType != models.USER_TYPE_ADMIN {
		util.OutPutError(403,"用户类型异常")
		return
	}
	controllers.UserId = claims.UserId
}